package com.small.nacos.client.config.impl;

import com.alibaba.nacos.api.common.Constants;
import small.common.core.io.util.ConcurrentDiskUtil;
import small.common.core.io.util.FileIoUtil;
import small.common.core.system.util.JvmUtil;
import small.common.core.util.StringUtil;
import com.small.nacos.client.utils.SnapShotSwitch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;

/**
 * 配置执行器
 *
 * @Author zhoujin
 * @Date 2022/11/18 15:20
 */
public class LocalConfigInfoProcessor {

    private final static Logger LOGGER = LoggerFactory.getLogger(LocalConfigInfoProcessor.class);

    /**
     * 本地故障转移配置文件地址
     */
    protected static String LOCAL_SNAPSHOT_PATH = "";

    static {
        //用户系统路径 C:\Users\25098\
        LOCAL_SNAPSHOT_PATH = System.getProperty("JM.SNAPSHOT.PATH", System.getProperty("user.home")) + File.separator + "nacos" + File.separator + "config";
    }

    /**
     * 获取故障转移文件内容
     * @param serverName
     * @param dataId
     * @param group
     * @param tenant
     * @return
     */
    public static String getFailover(String serverName, String dataId, String group, String tenant) {
        File localPath = getFailoverFile(serverName, dataId, group, tenant);
        if (!localPath.exists() || !localPath.isFile()) {
            return null;
        }

        try {
            return FileIoUtil.readFile(localPath);
        } catch (IOException ioe) {
            LOGGER.error("[" + serverName + "] get failover error, " + localPath, ioe);
            return null;
        }
    }

    /**
     * 获取故障转移文件
     * @param serverName
     * @param dataId
     * @param group
     * @param tenant
     * @return
     */
    static File getFailoverFile(String serverName, String dataId, String group, String tenant) {
        File tmp = new File(LOCAL_SNAPSHOT_PATH, serverName + "_nacos");
        tmp = new File(tmp, "data");
        if (StringUtil.isBlank(tenant)) {
            tmp = new File(tmp, "config-data");
        } else {
            tmp = new File(tmp, "config-data-tenant");
            tmp = new File(tmp, tenant);
        }
        return new File(new File(tmp, group), dataId);
    }

    /**
     * 保存临时配置文件
     * @param envName
     * @param dataId
     * @param group
     * @param tenant
     * @param config
     */
    public static void saveSnapshot(String envName, String dataId, String group, String tenant, String config) {
        if (!SnapShotSwitch.getIsSnapShot()) {
            return;
        }
        //获取快照文件
        File file = getSnapshotFile(envName, dataId, group, tenant);
        if (null == config) {
            try {
                com.alibaba.nacos.common.utils.IoUtils.delete(file);
            } catch (IOException ioe) {
                LOGGER.error("[" + envName + "] delete snapshot error, " + file, ioe);
            }
        } else {
            try {
                File parentFile = file.getParentFile();
                if (!parentFile.exists()) {
                    boolean isMdOk = parentFile.mkdirs();
                    if (!isMdOk) {
                        LOGGER.error("[{}] save snapshot error", envName);
                    }
                }

                if (JvmUtil.isMultiInstance()) {
                    ConcurrentDiskUtil.writeFileContent(file, config, Constants.ENCODE);
                } else {
                    com.alibaba.nacos.common.utils.IoUtils.writeStringToFile(file, config, Constants.ENCODE);
                }
            } catch (IOException ioe) {
                LOGGER.error("[" + envName + "] save snapshot error, " + file, ioe);
            }
        }
    }

    /**
     * 获取临时文件内容
     * @param name
     * @param dataId
     * @param group
     * @param tenant
     * @return
     */
    public static String getSnapshot(String name, String dataId, String group, String tenant) {
        if (!SnapShotSwitch.getIsSnapShot()) {
            return null;
        }
        File file = getSnapshotFile(name, dataId, group, tenant);
        if (!file.exists() || !file.isFile()) {
            return null;
        }

        try {
            return FileIoUtil.readFile(file);
        } catch (IOException ioe) {
            LOGGER.error("[" + name + "]+get snapshot error, " + file, ioe);
            return null;
        }
    }

    /**
     * 获取临时配置文件
     * @param envName
     * @param dataId
     * @param group
     * @param tenant
     * @return
     */
    static File getSnapshotFile(String envName, String dataId, String group, String tenant) {
        File tmp = new File(LOCAL_SNAPSHOT_PATH, envName + "_nacos");
        if (com.alibaba.nacos.common.utils.StringUtils.isBlank(tenant)) {
            tmp = new File(tmp, "snapshot");
        } else {
            tmp = new File(tmp, "snapshot-tenant");
            tmp = new File(tmp, tenant);
        }

        return new File(new File(tmp, group), dataId);
    }
    public static void cleanAllSnapshot() {
        try {
            File rootFile = new File(LOCAL_SNAPSHOT_PATH);
            File[] files = rootFile.listFiles();
            if (files == null || files.length == 0) {
                return;
            }
            for (File file : files) {
                if (file.getName().endsWith("_nacos")) {
                    FileIoUtil.cleanDirectory(file);
                }
            }
        } catch (IOException ioe) {
            LOGGER.error("clean all snapshot error, " + ioe.toString(), ioe);
        }
    }
}
